package com.xgkj.diyiketang.yizhibo;


import android.animation.ObjectAnimator;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.constant.WBConstants;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.utils.Utility;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.xgkj.diyiketang.EatShowApp;
import com.xgkj.diyiketang.ProtocolConst;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.activity.BaseActivity;
import com.xgkj.diyiketang.activity.WbcallbackActivity;
import com.xgkj.diyiketang.activity.data.AudieceAdapter;
import com.xgkj.diyiketang.activity.data.LiveLiuYanAdapter;
import com.xgkj.diyiketang.data.AudieceInfo;
import com.xgkj.diyiketang.data.DynamicInfo;
import com.xgkj.diyiketang.data.EatShowUserInfo;
import com.xgkj.diyiketang.data.LiveParentInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.http.engine.TaskEventListener;
import com.xgkj.diyiketang.task.LiveCommentTask;
import com.xgkj.diyiketang.task.LiveDetailTask;
import com.xgkj.diyiketang.task.LiveDynamicTask;
import com.xgkj.diyiketang.task.LiveOverTask;
import com.xgkj.diyiketang.task.StartLiveTask;
import com.xgkj.diyiketang.task.UpYZBUserIdTask;
import com.xgkj.diyiketang.util.AccessTokenKeeper;
import com.xgkj.diyiketang.util.DialogUtil;
import com.xgkj.diyiketang.util.ImageCache;
import com.xgkj.diyiketang.util.PalLog;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.util.ViewUtil;
import com.xgkj.diyiketang.util.WeixinShareUtil;
import com.xgkj.diyiketang.weidget.GifView;
import com.xgkj.diyiketang.weidget.HorizontalGridView;
import com.xgkj.eatshow.wxapi.WXEntryActivity;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.ref.SoftReference;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

public class RecorderActivity extends BaseActivity{ //implements IWeiboHandler.Response, View.OnClickListener, LiveLiuYanAdapter.LiwuListener {
   /* private static final String TAG = "RecorderActivity";

    private static final int REQUEST_CODE_REGISTER = 1;

    private static final int MSG_REFRESH_START_TIME = 101;
    private MyHandler mHandler;

    //    protected TextView mVideoTopicTv;
//    protected TextView mVideoTitleTv;
    //protected TextView mDurationTv;
    protected View mTopInfoAreaView;

    private View mOptionsView;

    private Dialog mNetworkInvalidDialog;
    private Dialog mConfirmStopDialog;
    private Dialog mVideoStoppedDialog;

    private YZBCameraPreview mCameraPreview;
    private YZBSdk mYzbSdk;

    private long mStartTime;

    private String mVid;

    private String mLiveTitle;

    private PowerManager.WakeLock mWakeLock;

    private String imageId;
    private String titleString;
    private int startLiveTaskId = -1;
    private int getAnchorTaskId = -1;
    private int getDynamicListTaskId = -1;
    private ImageView mZhuBoImg;
    private TextView mZhuBoNick;
    private TextView mGuankanshu;
    EatShowUserInfo userinfo;
    //    HorizontalScrollView horizontalScrollView;
    HorizontalGridView mAudieGridList;
    //    DisplayMetrics dm;
//    private int NUM = 5; // 每行显示个数
//
//    private int LIEWIDTH;//每列宽度
//    private int LIE = 20;//列数
    private List<DynamicInfo> dynamicList;
    private List<AudieceInfo> audienceList;
    private AudieceAdapter adapter;
    private ListView lyListView;
    private LiveLiuYanAdapter lyAdapter;
    private ImageView huifuBtn;
    private LinearLayout huifuLayout;
    private RelativeLayout mCaoZuoLayout;
    private EditText mPingLunEdit;
    private Button mPingLunBtn;
    private String cmtText;
    private int cmtTaskId = -1;
    //    private Timer timer;
//    private Context mContext;
    private String curtime;
    private String dynamciTime;
    private ImageView mCloseView;
    private int overTaskId = -1;
    private String mYZBUserId;
    private int upYZbuseridTaskId = -1;
    private ImageView mShareImg;
    private PopupWindow popWindow;
    private String share_path;
    private Context mContext;
    private WeixinShareReceive mWeixinShareReceive;
    private String weixinsharetype;
    private String weixinuseropenid;
    private String weibouserid;
    private Bitmap weiboShareBitmap;
    private byte[] weixinshareByte;
    private IWXAPI api;
    private IWeiboShareAPI mWeiboShareAPI = null;
    private String shoucangtype;
    public static Tencent mTencent;
    private String share_title;
    private RelativeLayout mAllLayout;
    private String mBusinessId;
    private InputMethodManager in;
    //加了直播类型
    private int liveType;
    private String charge_amount;
    private String live_pwd;
    private int liveIsOpen;
    private int isXubo;
    private String descString;
    private String liveCateString;
    private String zhiboId;
    private Button zhiboDescBtn;
    private PopupWindow descPopWindow;
    private TextView desc_title;
    private TextView desc_content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_recorder);
        mContext = this;
        Intent intent = getIntent();
        if (intent != null){
            mBusinessId = intent.getStringExtra("BUSINESSID");
        }
        in = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        mTencent = Tencent.createInstance(ProtocolConst.QQ_ID, this.getApplicationContext());
        api = WXAPIFactory.createWXAPI(mContext, ProtocolConst.APP_ID);
        mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this,
                ProtocolConst.WEIBO_APP_KEY);//这粒要换
        mWeiboShareAPI.registerApp();
        if (savedInstanceState != null) {
            mWeiboShareAPI.handleWeiboResponse(getIntent(), this);
        }
        mHandler = new MyHandler(this);
        initUIComponents();
        initListeners();

        mYzbSdk = YZBSdkFactory.getInstance().getYZBSdkInstance(this, Constants.APP_KEY_ID);
        mYzbSdk.registerApp(Constants.APP_KEY_ID, Constants.APP_KEY_SECRET);

        //初始化直播模块
        mYzbSdk.initStreamer();

        //设置错误、信息回调
        mYzbSdk.setOnErrorListener(mErrorListener);
        mYzbSdk.setOnInfoListener(mInfoListener);

        //设置相机预览的窗口
        mYzbSdk.setCameraPreview(mCameraPreview);

        //调用SDK对应的onCreate函数
        mYzbSdk.onCreate();

        //设置直播标题，直播标题为空不能开启直播
        mYzbSdk.setTitle(titleString);

        //获取用户登陆的session信息，登陆或注册成功后缓存该信息
        String sessionId = Preferences.getInstance(getApplicationContext()).getSessionId();
        String userId = Preferences.getInstance(getApplicationContext()).getUserNumber();
        PalLog.e(TAG, "sessionId:" + sessionId + "userId:" + userId);

//        String userId = Preferences.getInstance(getApplicationContext()).getUserNumber();
//        PalLog.e(TAG, "我的用户id"+userId);
        if (sessionId.isEmpty()) {
            //session信息为空，走登陆或注册的流程
            userLogin();
        } else {
            //获取到有效的session，直接开始直播
            mYzbSdk.liveStart(sessionId);
        }

        Thread.currentThread().setName("main thread");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeMessages(MSG_REFRESH_START_TIME);
        mHandler.removeMessages(111);
        liveStop(true);
        if (null != mYzbSdk) {
            mYzbSdk.onDestroy();
        }
    }

    private float currentX, currentY, scrollX, scrollY;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            currentX = event.getRawX();
            currentY = event.getRawY();
        } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
            scrollX = event.getRawX();
            scrollY = event.getRawY();


        } else if (event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_UP) {

        }
        return super.onTouchEvent(event);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.

        return super.onOptionsItemSelected(item);
    }

    private void initUIComponents() {
        Intent intent = getIntent();
        zhiboId = intent.getStringExtra("ID");
        imageId = intent.getStringExtra("FENGMIANID");
        titleString = intent.getStringExtra("TITLE");
        isXubo = intent.getIntExtra("isXubo", 0);
        mYZBUserId = intent.getStringExtra("YZBUSERID");
        liveType = intent.getIntExtra("LIVE_TYPE", 0);
        liveIsOpen = intent.getIntExtra("IS_OPEN", 1);
        if (liveType == 1) {
            charge_amount = intent.getStringExtra("AMOUNT");
        } else if (liveType == 2) {
            live_pwd = intent.getStringExtra("PWD");
        }
        descString = intent.getStringExtra("DESC");
        liveCateString = intent.getStringExtra("LIVECATE");

        PalLog.e("图片id+title", imageId + "~~~~~~~~~~~~" + titleString);
        mAllLayout = (RelativeLayout) findViewById(R.id.all_layout);
        mZhuBoImg = (ImageView) findViewById(R.id.zhubo_img);
        mZhuBoNick = (TextView) findViewById(R.id.zhubo_nick);
        mGuankanshu = (TextView) findViewById(R.id.guankanshu);
//        horizontalScrollView = (HorizontalScrollView) findViewById(R.id.scrollView);
        mAudieGridList = (HorizontalGridView) findViewById(R.id.audie_list);
        adapter = new AudieceAdapter(this);
        mAudieGridList.setAdapter(adapter);


//        horizontalScrollView.setHorizontalScrollBarEnabled(false);// 隐藏滚动条
//        getScreenDen();
//        LIEWIDTH = dm.widthPixels / NUM;
        setValue();


        lyListView = (ListView) findViewById(R.id.liuyan_list);
        lyAdapter = new LiveLiuYanAdapter(mContext);
        lyAdapter.setLiwuListener(this);
        lyListView.setAdapter(lyAdapter);
//        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                if(mListView.getHeaderViewsCount()>0){
//                    position--;
//                }
//                if (position<0)return;
//                SellerInfo info = (SellerInfo) mAdapter.getItem(position);
//                Intent intent = new Intent();
//                intent.putExtra("SJNAME", info.getBusinessName());
//                intent.putExtra("SJID",info.getBusinessId());
//                //设置返回数据
//                ShangJiaListActivity.this.setResult(RESULT_OK, intent);
//                //关闭Activity
//                ShangJiaListActivity.this.finish();
//            }
//        });

        huifuBtn = (ImageView) findViewById(R.id.live_huifu);
        huifuBtn.setOnClickListener(this);
        huifuLayout = (LinearLayout) findViewById(R.id.huifu_layout);

        mAllLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (huifuLayout.getVisibility() == View.VISIBLE) {
                    huifuLayout.setVisibility(View.GONE);
                    huifuBtn.setVisibility(View.VISIBLE);
                    mCaoZuoLayout.setVisibility(View.VISIBLE);
                    mShareImg.setVisibility(View.VISIBLE);
                    try {
                        in.hideSoftInputFromWindow(RecorderActivity.this.getCurrentFocus().getWindowToken(), 0);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
        });

        mCaoZuoLayout = (RelativeLayout) findViewById(R.id.live_options_right_ll);

        mPingLunEdit = (EditText) findViewById(R.id.pinglun);
        mPingLunBtn = (Button) findViewById(R.id.fabiaopinglun);
        mPingLunBtn.setOnClickListener(this);
        mCloseView = (ImageView) findViewById(R.id.guanbi);
        mCloseView.setOnClickListener(this);
        mShareImg = (ImageView) findViewById(R.id.live_share);
        mShareImg.setOnClickListener(this);
        mCameraPreview = (YZBCameraPreview) this.findViewById(R.id.camera_preview);

//        mTopInfoAreaView = this.findViewById(R.id.live_info_rl);
//        mVideoTopicTv = (TextView) findViewById(R.id.player_category_tv);
//        mVideoTitleTv = (TextView) findViewById(R.id.player_title_tv);
//        mDurationTv = (TextView) findViewById(R.id.player_duration_tv);

        mOptionsView = this.findViewById(R.id.live_options_right_ll);
//        liwuImageView = (GifView) findViewById(R.id.liwu_imageview);
        liwuImageView = (GifImageView) findViewById(R.id.liwu_imageview);
        liwuTanKuang = (LinearLayout) findViewById(R.id.liwutankuang);
        zhiboDescBtn = (Button) findViewById(R.id.zhibo_desc);
        zhiboDescBtn.setOnClickListener(this);
        initDescPopWindow();
        initPopWindow();
    }


    private void setValue() {
        LayoutParams params = new LayoutParams(adapter.getCount() * ViewUtil.dip2px(mContext, 32),
                ViewUtil.dip2px(mContext, 40));
        mAudieGridList.setLayoutParams(params);
        mAudieGridList.setColumnWidth(ViewUtil.dip2px(mContext, 32));
        mAudieGridList.setStretchMode(GridView.NO_STRETCH);
        int count = adapter.getCount();
        mAudieGridList.setNumColumns(count);
    }

//    private void getScreenDen() {
//        dm = new DisplayMetrics();
//        getWindowManager().getDefaultDisplay().getMetrics(dm);
//    }

    private void initListeners() {
        mOptionsView.findViewById(R.id.live_stop_iv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isFinishing()) {
                    showConfirmStopDialog();
                }
            }
        });

        CheckBox cameraSwitchCb = (CheckBox) mOptionsView.findViewById(R.id.live_switch_camera_cb);
        cameraSwitchCb.setOnCheckedChangeListener(mOnCheckedChangeListener);

        CheckBox flashLightCb = (CheckBox) mOptionsView.findViewById(R.id.live_flash_cb);
        flashLightCb.setOnCheckedChangeListener(mOnCheckedChangeListener);
    }

    private CompoundButton.OnCheckedChangeListener mOnCheckedChangeListener =
            new CompoundButton.OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    switch (buttonView.getId()) {
                        case R.id.live_switch_camera_cb:
                            if (mYzbSdk != null) {
                                mYzbSdk.switchCamera();
                            }

                            CheckBox checkBox = (CheckBox) mOptionsView.findViewById(R.id.live_flash_cb);
                            checkBox.setEnabled(isChecked);
                            if (isChecked) {
                                checkBox.setChecked(false);
                            }
                            break;
                        case R.id.live_flash_cb:
                            if (mYzbSdk != null) {
                                mYzbSdk.switchFlashlight();
                            }
                            break;
                    }
                }
            };

    @Override
    protected void onResume() {
        super.onResume();
        doFresh();
        if (null != mYzbSdk) {
            mYzbSdk.onResume();
            mHandler.sendEmptyMessage(MSG_REFRESH_START_TIME);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        // timer.cancel();
        if (null != mYzbSdk) {
            mYzbSdk.onPause();
            mHandler.removeMessages(MSG_REFRESH_START_TIME);
        }
        mHandler.removeMessages(111);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case REQUEST_CODE_REGISTER:
                if (null != data) {
                    String sessionId = data.getStringExtra(Constants.EXTRA_KEY_SESSION_ID);
                    PalLog.d(TAG, "session id: " + sessionId);
                    if (!TextUtils.isEmpty(sessionId)) {
                        if (null != mYzbSdk) {
                            mYzbSdk.setOnErrorListener(mErrorListener);
                            mYzbSdk.setOnInfoListener(mInfoListener);
                            mYzbSdk.liveStart(sessionId);
                        }
                    }
                }
                break;
        }
    }

    @Override
    public void onBackPressed() {
        showConfirmStopDialog();
    }

    private void showNetworkInvalidDialog() {
        if (isFinishing()) {
            return;
        }
        if (mNetworkInvalidDialog == null) {
            mNetworkInvalidDialog = Utils.getOneButtonDialog(this,
                    getResources().getString(R.string.no_network_dialog), false, false,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            setResult(RESULT_OK);
                            finish();
                        }
                    });
        }
        mNetworkInvalidDialog.show();
    }

    private void showVideoStoppedDialog() {
        if (isFinishing()) {
            return;
        }
        if (mVideoStoppedDialog == null) {
            mVideoStoppedDialog = Utils.getOneButtonDialog(this,
                    getResources().getString(R.string.video_stopped_by_server_dialog), false, false,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            setResult(RESULT_OK);
                            finish();
                        }
                    });
        }
        mVideoStoppedDialog.show();
    }

    private void showToastOnUiThread(final int resId) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (isFinishing()) {
                    return;
                }

                ToastUtil.showMessage(getApplicationContext(), resId);
                finish();
            }
        });
    }

    private void userRegister() {
//        mYzbSdk.register(Constants.USER_TOKEN, "nickname", new YZBSdk.ApiRequestCallBack<String>() {
        String phone = EatShowApp.getInstance().getmUserInfo().getPhoneNum();
        String nickname = EatShowApp.getInstance().getmUserInfo().getNickName();
        mYzbSdk.register(phone, nickname, new YZBSdk.ApiRequestCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                if (!TextUtils.isEmpty(result)) {
                    if (null != mYzbSdk) {
                        mYzbSdk.setOnErrorListener(mErrorListener);
                        mYzbSdk.setOnInfoListener(mInfoListener);
                        mYzbSdk.liveStart(result);
                    }
                }
            }

            @Override
            public void onError(String errorInfo) {
                PalLog.e(TAG, "on error:" + errorInfo + "易直播id：" + mYzbSdk.getUserNumber());

                *//**
                 * windo on 16/10/31
                 * 13:59
                 * 修改 错误信息是E_USER_EXISTS表示已经注册过，但是不知道Y_userId
                 *//*
                if (errorInfo != null && errorInfo.equals("E_USER_EXISTS")) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showRegisterErrorDialog();
                            return;
                        }
                    });
                }

                if (mYzbSdk.getUserNumber() != null) {
                    userLogin();
                }

//                ToastUtil.showMessage(getApplicationContext(), R.string.msg_registered_errer);
            }

            @Override
            public void onFailure(String msg) {
                PalLog.e(TAG, "on Failure");
//                ToastUtil.showMessage(getApplicationContext(), R.string.msg_registered_errer);
            }
        });
    }

    private Dialog mRegisterErrorDiaglog;

    private void showRegisterErrorDialog() {
        if (isFinishing()) {
            return;
        }

        if (mRegisterErrorDiaglog == null) {
            mRegisterErrorDiaglog = Utils.getOneButtonDialog(this, getResources().getString(R.string.already_register_but_error), false, false, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    setResult(RESULT_OK);
                    finish();
                }
            });
        }
        mRegisterErrorDiaglog.show();

    }

    private void userLogin() {
        //get user id
        String userId = null;
        if (TextUtils.isEmpty(mYZBUserId)) {
            userId = Preferences.getInstance(getApplicationContext()).getUserNumber();
        } else {
            userId = mYZBUserId;
        }

        Log.e("我登录的用户id", userId);

        if (ViewUtil.isNull(userId)) {
            if (isFinishing()) {
                return;
            }
            userRegister();
        } else {
            mYzbSdk.userLogin(EatShowApp.getInstance().getmUserInfo().getPhoneNum(), userId, new YZBSdk.ApiRequestCallBack<String>() {
                @Override
                public void onSuccess(String result) {
                    Preferences.getInstance(getApplicationContext()).putString(Preferences.KEY_SESSION_ID, result);
                    if (null != mYzbSdk) {
                        mYzbSdk.liveStart(result);
                    }
                }

                @Override
                public void onError(String errorInfo) {
                    PalLog.e(TAG, "Error:" + errorInfo);

                    if (isFinishing()) {
                        return;
                    }
//                    ToastUtil.showMessage(getApplicationContext(), R.string.msg_login_error);
//
//                    Utils.getButtonsDialog(RecorderActivity.this,
//                            getString(R.string.dialog_title_phone_register), false, false,
//                            new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//                                    Intent intent = new Intent(getApplicationContext(),
//                                            RegistActivity.class);
//                                    intent.putExtra(Constants.EXTRA_KEY_PHONE_NUMBER, Constants.USER_TOKEN);
//                                    startActivityForResult(intent, REQUEST_CODE_REGISTER);
//                                }
//                            }, new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//                                    finish();
//                                }
//                            }).show();

                    userRegister();
                }

                @Override
                public void onFailure(String msg) {
                    PalLog.e(TAG, "Failure: " + msg);

                    if (isFinishing()) {
                        return;
                    }
                    ToastUtil.showMessage(getApplicationContext(), R.string.msg_network_bad_check_retry);
                    finish();
                }
            });

        }
    }

    private IYZBSdk.OnErrorListener mErrorListener = new IYZBSdk.OnErrorListener() {
        @Override
        public boolean onError(int what) {
            switch (what) {
                case IYZBSdk.STREAMER_ERROR_VERSION_LOW:
                    showToastOnUiThread(R.string.title_version_not_supported);
                    break;
                case IYZBSdk.STREAMER_ERROR_OPEN_CAMERA:
                    showToastOnUiThread(R.string.title_call_camera_error);
                    break;
                case IYZBSdk.STREAMER_ERROR_CREATE_AUDIORECORD:
                    showToastOnUiThread(R.string.title_audio_record_error);
                    break;
                case IYZBSdk.STREAMER_ERROR_STARTING:
                    break;
                case IYZBSdk.STREAMER_ERROR_RECONNECT:
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mHandler.removeMessages(MSG_REFRESH_START_TIME);
                            showNetworkInvalidDialog();
                        }
                    });

                    break;
                case IYZBSdk.STREAMER_ERROR_STOPPED_BY_SERVER:
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mHandler.removeMessages(MSG_REFRESH_START_TIME);
                            showVideoStoppedDialog();
                        }
                    });
                    break;
                case IYZBSdk.SDK_ERROR_NET_REQUEST_FAILED:
                    showToastOnUiThread(R.string.msg_network_bad_check_retry);
                    break;
                case IYZBSdk.SDK_ERROR_SESSION_ID:
                    //session was invalid, relogin
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (null != mYzbSdk) {
                                userLogin();
                            }
                        }
                    });

                    break;
                case IYZBSdk.STREAMER_ERROR_VIDEO_ALREADY_STOPPED:
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (isFinishing()) {
                                return;
                            }
                            Dialog dialog = Utils.getOneButtonDialog(RecorderActivity.this,
                                    getString(R.string.dialog_title_live_stop), false, false,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            setResult(RESULT_OK);
                                            finish();
                                        }
                                    });
                            dialog.show();
                        }
                    });

                    break;
                case IYZBSdk.SDK_ERROR_APPKEY_INVALID:
                    showToastOnUiThread(R.string.msg_appkey_invalid);
                    break;
                case IYZBSdk.SDK_ERROR_LACK_SMS_VERIFY:
                    showToastOnUiThread(R.string.msg_register_sms_verify);
                    break;
                case IYZBSdk.SDK_ERROR_INVALID_PHONE:
                    showToastOnUiThread(R.string.msg_invalid_phone);
                    break;
                case IYZBSdk.STREAMER_ERROR_INVALID_TITLE:
                    showToastOnUiThread(R.string.msg_invalid_title);
                    break;
            }
            return true;
        }
    };

    private IYZBSdk.OnInfoListener mInfoListener = new IYZBSdk.OnInfoListener() {
        @Override
        public boolean onInfo(int what) {
            switch (what) {
                case IYZBSdk.STREAMER_INFO_RECONNECTING:
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (isFinishing()) {
                                return;
                            }
                            ToastUtil.showMessage(getApplicationContext(), R.string.network_invalid_try_reconnect);
                            mHandler.removeMessages(MSG_REFRESH_START_TIME);
                        }
                    });

                    break;
                case IYZBSdk.STREAMER_INFO_RECONNECTED:
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (isFinishing()) {
                                return;
                            }
                            ToastUtil.showMessage(getApplicationContext(), R.string.network_ok_message);
                            mHandler.sendEmptyMessage(MSG_REFRESH_START_TIME);
                        }
                    });

                    break;
                case IYZBSdk.STREAMER_INFO_START_SUCCESS:
                    break;
                case IYZBSdk.STREAMER_INFO_STREAMING:
                    break;
                case IYZBSdk.STREAMER_INFO_STREAM_SUCCESS:
                    //get the video id
                    mVid = mYzbSdk.getVid();
                    Log.e("我的直播id", mVid);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            doStart();
                        }
                    });

                    acquireWakeLock();
                    mStartTime = System.currentTimeMillis();

                    String nickName = Preferences.getInstance(getApplicationContext()).getUserNickname();
                    if (TextUtils.isEmpty(nickName)) {
                        nickName = Constants.NICK_NAME;
                    }
                    mLiveTitle = getString(R.string.live_title_default, nickName, mVid);

//                    saveLiveVideoInfo(nickName, mLiveTitle, mVid, Utils.formatToDate(mStartTime));
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (isFinishing()) {
                                return;
                            }
//                            mDurationTv.setVisibility(View.VISIBLE);
                            mOptionsView.setVisibility(View.VISIBLE);
//                            mVideoTitleTv.setVisibility(View.VISIBLE);
//                            mVideoTitleTv.setText(mLiveTitle);
                            mHandler.sendEmptyMessage(MSG_REFRESH_START_TIME);
                        }
                    });
                    break;
                case IYZBSdk.SDK_INFO_REGISTER_SUCCESS:
                    if (null != mYzbSdk) {
                        Preferences.getInstance(getApplicationContext()).putString(Preferences.KEY_SESSION_ID,
                                mYzbSdk.getSessionId());
                        Preferences.getInstance(getApplicationContext()).putString(Preferences.KEY_USER_NUMBER,
                                mYzbSdk.getUserNumber());

                        mYZBUserId = Preferences.getInstance(getApplicationContext()).getUserNumber();
                        doUpYZBUserId();

                    }
                    break;
                case IYZBSdk.SDK_INFO_LOGOUT_SUCCESS:
                    Preferences.getInstance(getApplicationContext()).remove(Preferences.KEY_SESSION_ID);
                    break;
            }
            return true;
        }
    };

    private boolean isStart;

    private void doStart() {
        share_path = "http://app.sjmingze.com/yzb/yzb.html?vid=" + mVid + "";
        isStart = true;
        Log.e(TAG, "doStart: "+"vid:"+ mVid+","+"id:"+ zhiboId+","+"liveCover:"+ imageId+","+ "liveTitle:"+
                titleString+","+"businessId:"+ mBusinessId+","+ "isOpen:"+liveIsOpen+","+"liveType:" +liveType+","+"fee:" +charge_amount+","+ "psw:"+live_pwd+","+ "isLive:"+isXubo+","+",这有一个null"+ "liveCate"+liveCateString+","+"liveContent:"+ descString);
        StartLiveTask task = new StartLiveTask(mVid, zhiboId,imageId, titleString,liveIsOpen,liveType,charge_amount,live_pwd,isXubo,null,liveCateString,descString);
        task.addListener(doLiveListener);
        startLiveTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    private void doGetAnchorInfo() {
        LiveDetailTask dtask = new LiveDetailTask(mVid);
        dtask.addListener(doLiveListener);
        getAnchorTaskId = getEatShowApp().getTaskManager().addTask(dtask);
    }

    private void doLiveStop() {
        LiveOverTask overTask = new LiveOverTask(mVid);
        overTask.addListener(doLiveListener);
        overTaskId = getEatShowApp().getTaskManager().addTask(overTask);
    }

    private void getDynamicList() {
        if (dynamciTime == null) {
            Date date = new Date();
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            curtime = format.format(date);
            dynamciTime = curtime;
        }


        if (ViewUtil.isNull(mVid)) {
            return;
        }
        if (getDynamicListTaskId != -1) {
            return;
        }
        PalLog.e("动态时间", curtime);
        LiveDynamicTask dyTask = new LiveDynamicTask(mVid, dynamciTime, "20");
        dyTask.addListener(doLiveListener);
        getDynamicListTaskId = getEatShowApp().getTaskManager().addTask(dyTask);
    }

    private TaskEventListener doLiveListener = new ShowToastTaskEventListener(this) {
        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (taskId == startLiveTaskId) {
                PalLog.e("直播开始", "直播开始......");
                doGetAnchorInfo();
//                Timer timer = new Timer();
//                timer.schedule(new TimerTask() {
//                    public void run() {
                Date date = new Date();
                DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                curtime = format.format(date);

                dynamciTime = curtime;
                getDynamicList();
//                    }
//                }, 2000);// 设定指定的时间time,此处为2000毫秒


            } else if (taskId == getAnchorTaskId) {
                userinfo = (EatShowUserInfo) data;
                if (userinfo != null) {
                    String liveContent = userinfo.getLiveContent();
                    try {
                        desc_title.setText(URLDecoder.decode(userinfo.getLiveTitle(), "utf-8"));
                        liveContent = URLDecoder.decode(liveContent, "utf-8");
                        desc_content.setText(liveContent);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    ImageCache.getInstance(mContext).loadBitmapToView(
                            mZhuBoImg,
                            userinfo.getUserLogo(),
                            new ViewUtil.Size(ViewUtil.dip2px(mContext, 32), ViewUtil.dip2px(
                                    mContext, 32)));
                    if (userinfo.getNickName() != null) {
                        try {
                            mZhuBoNick.setText(URLDecoder.decode(userinfo.getNickName(), "utf-8"));
                            share_title = URLDecoder.decode(userinfo.getNickName(), "utf-8") + "正在第一课堂直播，赶快点开吧！";
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } else if (taskId == getDynamicListTaskId) {
                getDynamicListTaskId = -1;
                LiveParentInfo lpInfo = (LiveParentInfo) data;
                mGuankanshu.setText(lpInfo.getViewCount() + "人");

                dynamicList = lpInfo.getDynamicList();

                if (dynamicList != null && dynamicList.size() > 0) {
                    lyAdapter.updateData(dynamicList);
                    lyListView.post(new Runnable() {
                        @Override
                        public void run() {
                            lyListView.smoothScrollToPosition(lyAdapter.getCount() - 1);
                        }
                    });
                    dynamciTime = dynamicList.get(dynamicList.size() - 1).getDynamicTime();
//                    PalLog.e("返回的动态时间", dynamciTime);

                }

                audienceList = lpInfo.getAudienceList();
                if (audienceList != null && audienceList.size() > 0) {
                    adapter.clearData();
                    adapter.updateData(audienceList);
                    setValue();

                }


            } else if (taskId == cmtTaskId) {
//                PalLog.e("评论成功", "lalala");
                DynamicInfo addInfo = new DynamicInfo();
                addInfo.setCommentContent(cmtText);
                addInfo.setUserName(EatShowApp.getInstance().getmUserInfo().getNickName());
                addInfo.setUserLevel(EatShowApp.getInstance().getmUserInfo().getUserLevel());
                addInfo.setDynamicType(1);
                List<DynamicInfo> dynamicList_self = new ArrayList<DynamicInfo>();
                dynamicList_self.add(addInfo);
                lyAdapter.updateData(dynamicList_self);
                lyListView.post(new Runnable() {
                    @Override
                    public void run() {
                        lyListView.setSelection(lyAdapter.getCount() - 1);
                    }
                });
            } else if (taskId == overTaskId) {
                PalLog.e("第一课堂", "直播结束返回");
            } else if (taskId == upYZbuseridTaskId) {
                PalLog.e("第一课堂", "上传易直播Userid成功");
            }

        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            if (taskId == getDynamicListTaskId) {
                getDynamicListTaskId = -1;
                super.handleTaskError(taskId, errorCode, errorMsg);
            } else if (taskId == startLiveTaskId) {
                Log.e(TAG, "handleTaskError: "+errorCode);
                if (errorCode == 8000111 || errorCode == 8006001) {
                    DialogUtil.createDialog(mContext, getString(R.string.prompt), errorMsg, getString(R.string.ok), new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            liveStop(false);
                        }
                    });
                }
            } else {
                super.handleTaskError(taskId, errorCode, errorMsg);
            }
        }

        @Override
        public void handleTaskMessage(int taskId, Object data) {
            super.handleTaskMessage(taskId, data);
        }
    };

    private void saveLiveVideoInfo(String nickname, String title, String vid, String start_time) {
        List<Map<String, String>> oldDatas = Preferences.getInstance(getApplicationContext()).
                getList(Preferences.KEY_VIDEO_LIST);

        Map<String, String> newVideo = new HashMap<String, String>();
        newVideo.put(Constants.KEY_NICK_NAME, nickname);
        newVideo.put(Constants.KEY_TITLE, title);
        newVideo.put(Constants.KEY_VIDEO_ID, vid);
        newVideo.put(Constants.KEY_START_TIME, start_time);
        oldDatas.add(newVideo);

        Preferences.getInstance(getApplicationContext()).putList(Preferences.KEY_VIDEO_LIST, oldDatas);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.live_huifu:
                huifuLayout.setVisibility(View.VISIBLE);
                mCaoZuoLayout.setVisibility(View.GONE);
                huifuBtn.setVisibility(View.GONE);
                mShareImg.setVisibility(View.GONE);

                break;
            case R.id.fabiaopinglun:
                huifuLayout.setVisibility(View.GONE);
                huifuBtn.setVisibility(View.VISIBLE);
                mCaoZuoLayout.setVisibility(View.VISIBLE);
                mShareImg.setVisibility(View.VISIBLE);
                try {
                    in.hideSoftInputFromWindow(RecorderActivity.this.getCurrentFocus().getWindowToken(), 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (checkInput()) {
                    publishComment();
                    mPingLunEdit.setText(null);
                }
                break;
            case R.id.guanbi:
                if (!isFinishing()) {
                    showConfirmStopDialog();
                }
                break;
            case R.id.live_share:
                popWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
                break;

            case R.id.share_to_timeline:
                weixinsharetype = "sharefriends";
                shareToWeiXin(share_path, true);
                popWindow.dismiss();
                break;
            case R.id.share_to_weixinfriend:
                weixinsharetype = "sharefriend";
                shareToWeiXin(share_path, false);
                popWindow.dismiss();
                break;
            case R.id.share_to_weibo:
                shareToWeiBo(share_path);
                popWindow.dismiss();
                break;
            case R.id.share_to_qq:
                final Bundle params = new Bundle();
                params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
                params.putString(QQShare.SHARE_TO_QQ_TITLE, "第一课堂");
                params.putString(QQShare.SHARE_TO_QQ_SUMMARY, share_title);
                params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, share_path);
                params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, "http://www.chiboker.com/diyiketangImage/diyiketang_icon.png");
                // params.putByteArray(QQShare.SHARE_TO_QQ_IMAGE_URL,weixinshareByte);
                params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "第一课堂");
                mTencent.shareToQQ(this, params, qqShareListener);
                popWindow.dismiss();
                break;

            case R.id.zhibo_desc:
                descPopWindow.showAtLocation(v, Gravity.CENTER, 0, 0);
                break;
            case R.id.close:
                descPopWindow.dismiss();
                break;

        }
    }

    private void publishComment() {
        LiveCommentTask cmtTask = new LiveCommentTask(mVid, cmtText);
        cmtTask.addListener(doLiveListener);
        cmtTaskId = getEatShowApp().getTaskManager().addTask(cmtTask);
    }

    private void doUpYZBUserId() {
        if (ViewUtil.isNull(mYZBUserId)) return;
        UpYZBUserIdTask upTask = new UpYZBUserIdTask(mYZBUserId);
        upTask.addListener(doLiveListener);
        upYZbuseridTaskId = getEatShowApp().getTaskManager().addTask(upTask);
    }

    private boolean checkInput() {
        cmtText = mPingLunEdit.getText().toString().trim();

        if (TextUtils.isEmpty(cmtText)) {
            Toast.makeText(mContext, R.string.no_cmt, Toast.LENGTH_SHORT)
                    .show();
            return false;
        }
        return true;
    }


    static class MyHandler extends Handler {
        private SoftReference<RecorderActivity> softReference;

        public MyHandler(RecorderActivity activity) {
            softReference = new SoftReference<RecorderActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            RecorderActivity activity = softReference.get();
            if (activity == null) {
                return;
            }
            switch (msg.what) {
//                case MSG_REFRESH_START_TIME:
//                    activity.mDurationTv.setText(Utils.getDurationTime(activity, activity.mStartTime,
//                            System.currentTimeMillis()));
//                    sendEmptyMessageDelayed(MSG_REFRESH_START_TIME, 1000);
//                    break;
                case 111:
                    activity.getDynamicList();
//                    PalLog.e(TAG,"22222222222222222222222222222");
                    activity.mHandler.sendEmptyMessageDelayed(111, 2000);
                    break;
                case 333:
                    activity.hideDonghua();
                    break;
                case 444:
                    activity.hiddenView1();
                    break;
                case 555:
                    activity.hiddenView2();
                    break;
            }
        }
    }

    private void showConfirmStopDialog() {
        if (mConfirmStopDialog != null) {
            mConfirmStopDialog.show();
            return;
        }
        mConfirmStopDialog = new android.app.AlertDialog.Builder(this)
                .setTitle(R.string.title_confirm_stop_live)
                .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        liveStop(true);
                    }
                })
                .setNegativeButton(R.string.cancel, null)
                .setOnKeyListener(new DialogInterface.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
                            dialog.dismiss();
                            return true;
                        }
                        return false;
                    }
                })
                .setCancelable(false)
                .create();
        mConfirmStopDialog.show();
    }

    private void liveStop(boolean isRequest) {
        if (isRequest) {
            doLiveStop();
        }
        releaseWakeLock();
        mHandler.removeMessages(MSG_REFRESH_START_TIME);
        if (mYzbSdk != null && isStart) {
            mYzbSdk.liveStop(Preferences.getInstance(getApplicationContext()).getSessionId(), mVid);
        }
        setResult(RESULT_OK);
        finish();
    }

    private void acquireWakeLock() {
        if (null == mWakeLock) {
            PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, TAG);
        }

        if (!mWakeLock.isHeld()) {
            mWakeLock.acquire();
        }
    }

    private void releaseWakeLock() {
        if (null != mWakeLock) {
            mWakeLock.release();
            mWakeLock = null;
        }
    }


    private void doFresh() {
        //PalLog.e(TAG,"1111111111111111111111");
        mHandler.sendEmptyMessageDelayed(111, 2000);

//        timer = new Timer();
//        timer.schedule(new TimerTask() {
//            public void run() {
//                getDynamicList();
//            }
//        }, 2000);// 设定指定的时间time,此处为2000毫秒
    }

    private void initDescPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.pop_desc, null);
        view.findViewById(R.id.close).setOnClickListener(this);
        desc_title = (TextView) view.findViewById(R.id.title);
        desc_content = (TextView) view.findViewById(R.id.desc);
        descPopWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        descPopWindow.setBackgroundDrawable(new ColorDrawable());
        descPopWindow.setFocusable(true);
        descPopWindow.setOutsideTouchable(true);
    }

    private void initPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.share_pop,
                null);
        ((ImageView) view.findViewById(R.id.share_to_timeline))
                .setOnClickListener(this);
        ((ImageView) view.findViewById(R.id.share_to_weixinfriend))
                .setOnClickListener(this);
        ((ImageView) view.findViewById(R.id.share_to_weibo))
                .setOnClickListener(this);
        ((ImageView) view.findViewById(R.id.share_to_qq))
                .setOnClickListener(this);
        popWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        popWindow.setBackgroundDrawable(new ColorDrawable());
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mWeiboShareAPI.handleWeiboResponse(intent, this);
    }

    @Override
    public void onResponse(BaseResponse baseResponse) {
        switch (baseResponse.errCode) {
            case WBConstants.ErrorCode.ERR_OK:
                Toast.makeText(this, R.string.weibosdk_toast_share_success,
                        Toast.LENGTH_LONG).show();
                //doShareWeiboGetPoint();
                break;
            case WBConstants.ErrorCode.ERR_CANCEL:
                Toast.makeText(this, R.string.weibosdk_toast_share_canceled,
                        Toast.LENGTH_LONG).show();
                break;
            case WBConstants.ErrorCode.ERR_FAIL:
                Toast.makeText(
                        this,
                        getString(R.string.weibosdk_toast_share_failed)
                                + "Error Message: " + baseResponse.errMsg,
                        Toast.LENGTH_LONG).show();
                break;
        }
    }

    class WeixinShareReceive extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println(intent.getAction());
            weixinuseropenid = intent.getStringExtra(ProtocolConst.WEIXIN_OPENID);

            if (intent.getAction().equalsIgnoreCase(WXEntryActivity.WEIXIN_SHARE_SUCCESS_ACTION)) {

            } else if (intent.getAction().equalsIgnoreCase(WbcallbackActivity.WEIBO_SHARE_SUCCESS_ACTION)) {

            }
            if (mWeixinShareReceive != null) {
                unregisterReceiver(mWeixinShareReceive);
                mWeixinShareReceive = null;
            }
        }

    }

    IUiListener qqShareListener = new IUiListener() {
        @Override
        public void onCancel() {

        }

        @Override
        public void onComplete(Object response) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onError(UiError e) {
            // TODO Auto-generated method stub

        }
    };


    private void shareToWeiXin(String shareUrl, boolean isTimeLine) {
        if (!api.isWXAppSupportAPI() || !api.isWXAppInstalled()) {
            Toast.makeText(mContext, R.string.need_weixin_app, Toast.LENGTH_SHORT).show();
            return;
        }

        if (mWeixinShareReceive != null) {
            unregisterReceiver(mWeixinShareReceive);
            mWeixinShareReceive = null;
        }

        if (mWeixinShareReceive == null) {
            mWeixinShareReceive = new WeixinShareReceive();
            IntentFilter filter = new IntentFilter();
            filter.addAction(WXEntryActivity.WEIXIN_SHARE_SUCCESS_ACTION);
            registerReceiver(mWeixinShareReceive, filter);
        }
        WXWebpageObject webPage = new WXWebpageObject();
        webPage.webpageUrl = shareUrl;
        WXMediaMessage msg = new WXMediaMessage(webPage);
        //msg.title = ppntitle;
        if (isTimeLine) {
            msg.title = share_title;
        } else {
            msg.title = "第一课堂";
        }
        msg.description = share_title;
        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.app_icon);
        weixinshareByte = WeixinShareUtil.bmpToByteArray(bmp, true);
        if (weixinshareByte != null && weixinshareByte.length != 0) {
            msg.thumbData = weixinshareByte;
        }
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = isTimeLine ? SendMessageToWX.Req.WXSceneTimeline
                : SendMessageToWX.Req.WXSceneSession;
        api.sendReq(req);
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis())
                : type + System.currentTimeMillis();
    }

    private void shareToWeiBo(String webpage) {

        if (mWeixinShareReceive != null) {
            unregisterReceiver(mWeixinShareReceive);
            mWeixinShareReceive = null;
        }

        if (mWeixinShareReceive == null) {
            mWeixinShareReceive = new WeixinShareReceive();
            IntentFilter filter = new IntentFilter();
            filter.addAction(WbcallbackActivity.WEIBO_SHARE_SUCCESS_ACTION);
            registerReceiver(mWeixinShareReceive, filter);
        }

        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();

        if (!TextUtils.isEmpty(webpage)) {
            TextObject textobject = new TextObject();
            textobject.text = "第一课堂";
            weiboMessage.textObject = textobject;
            WebpageObject mediaObject = new WebpageObject();
            mediaObject.identify = Utility.generateGUID();
            mediaObject.defaultText = "第一课堂";
            mediaObject.title = "第一课堂";
            mediaObject.description = share_title;
            mediaObject.actionUrl = webpage;
            if (weiboShareBitmap != null) {
                mediaObject.setThumbImage(weiboShareBitmap);
            } else {
                mediaObject.setThumbImage(BitmapFactory.decodeResource(
                        getResources(), R.drawable.app_icon));
            }
            weiboMessage.mediaObject = mediaObject;
        }

        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
        // 用transaction唯一标识一个请求
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.multiMessage = weiboMessage;

        // 3. 发送请求消息到微博，唤起微博分享界面
        AuthInfo authInfo = new AuthInfo(this, ProtocolConst.WEIBO_APP_KEY, ProtocolConst.WEIBO_REDIRECT_URL, ProtocolConst.WEIBO_SCOPE);
        Oauth2AccessToken accessToken = AccessTokenKeeper.readAccessToken(getApplicationContext());
        String token = "";
        if (accessToken != null) {
            token = accessToken.getToken();
            weibouserid = accessToken.getUid();
        }
        mWeiboShareAPI.sendRequest(this, request, authInfo, token, new WeiboAuthListener() {


            @Override
            public void onWeiboException(WeiboException arg0) {
            }

            @Override
            public void onComplete(Bundle bundle) {
                Oauth2AccessToken newToken = Oauth2AccessToken.parseAccessToken(bundle);
                AccessTokenKeeper.writeAccessToken(getApplicationContext(), newToken);
                weibouserid = newToken.getUid();
//                    Toast.makeText(getApplicationContext(), "UID = "+weiboOpenId+"onAuthorizeComplete token = " + newToken.getToken(), 0).show();
            }

            @Override
            public void onCancel() {
            }
        });


    }


    *//**
     * 礼物相关
     *//*

    private View tankuangView1, tankuangView2;
    private ImageView headImage1, headImage2, liwuIcon1, liwuIcon2;
    private TextView dengjiText1, dengjiText2, shuliang1, shuliang2, liwuNick1, liwuNick2;
    private long view1time, view2time;
    private ObjectAnimator textScaleAnimation1;
    private ScaleAnimation textScaleAnimation2;
    private AnimationSet textAnimation;
    private LinearLayout liwuTanKuang;
    //    private ImageView liwuImageView;
//    private GifView liwuImageView;
    private GifImageView liwuImageView;


    private void hideDonghua() {
        liwuImageView.setVisibility(View.GONE);
        GifDrawable gifFromResource = (GifDrawable) liwuImageView.getDrawable();
        if (gifFromResource != null && !gifFromResource.isRecycled()) {
            gifFromResource.recycle();
        }
    }

    private void hiddenView1() {
        liwuTanKuang.removeView(tankuangView1);
        if (tankuangView2 != null && tankuangView2.getParent() != null) {
            liwuTanKuang.removeView(tankuangView2);
            liwuTanKuang.addView(tankuangView2);
        }
    }

    private void hiddenView2() {
        liwuTanKuang.removeView(tankuangView2);
    }

    private void showView1() {
        if (tankuangView1 != null && tankuangView1.getParent() == null) {
            liwuTanKuang.addView(tankuangView1);
        }
    }

    private void showView2() {
        if (tankuangView2 != null && tankuangView2.getParent() == null) {
            liwuTanKuang.addView(tankuangView2);
        }
    }

    private void initAnimation(View view) {
        textScaleAnimation1 = ObjectAnimator.ofFloat(view, View.SCALE_Y, 0.8f, 1.2f, 1f);
        textScaleAnimation1.setDuration(500);
        textScaleAnimation1.start();
    }


    private void tankuang(EatShowUserInfo info, String giftId, int count) {
        int liwuId = getResources().getIdentifier("t_" + giftId, "drawable", getPackageName());
        if (tankuangView1 == null) {
            tankuangView1 = LayoutInflater.from(mContext).inflate(R.layout.liwutankuang, liwuTanKuang, false);
            tankuangView1.setBackgroundResource(R.drawable.tankuang);
            headImage1 = (ImageView) tankuangView1.findViewById(R.id.head_img);

            dengjiText1 = (TextView) tankuangView1.findViewById(R.id.dengji);
            liwuNick1 = (TextView) tankuangView1.findViewById(R.id.nickname);
            liwuIcon1 = (ImageView) tankuangView1.findViewById(R.id.liwu_icon);
            shuliang1 = (TextView) tankuangView1.findViewById(R.id.count);
            shuliang1.getPaint().setShadowLayer(1, 2, 2, getResources().getColor(R.color.red));
            tankuangView1.setTag(info.getUserId());
            liwuTanKuang.addView(tankuangView1);
            mHandler.removeMessages(444);
            mHandler.sendEmptyMessageDelayed(444, 3000);
        }

        if (tankuangView2 == null && !info.getUserId().equals(tankuangView1.getTag())) {
            tankuangView2 = LayoutInflater.from(mContext).inflate(R.layout.liwutankuang, liwuTanKuang, false);
            tankuangView2.setBackgroundResource(R.drawable.tankuang);
            headImage2 = (ImageView) tankuangView2.findViewById(R.id.head_img);
            dengjiText2 = (TextView) tankuangView2.findViewById(R.id.dengji);
            liwuIcon2 = (ImageView) tankuangView2.findViewById(R.id.liwu_icon);
            shuliang2 = (TextView) tankuangView2.findViewById(R.id.count);
            shuliang2.getPaint().setShadowLayer(1, 2, 2, getResources().getColor(R.color.red));
            liwuNick2 = (TextView) tankuangView2.findViewById(R.id.nickname);
            tankuangView2.setTag(info.getUserId());
            liwuTanKuang.addView(tankuangView2);
            mHandler.removeMessages(555);
            mHandler.sendEmptyMessageDelayed(555, 3000);
        }

        if (info.getUserId().equals(tankuangView1.getTag())) {
            ImageCache.getInstance(mContext).loadBitmapToView(headImage1, info.getUserLogo(), ViewUtil.getHeadImageSize_40(mContext));
            dengjiText1.setText(info.getUserLevel());
            liwuIcon1.setImageResource(liwuId);
            liwuNick1.setText(URLDecoder.decode(info.getNickName()));
            count++;
            shuliang1.setText(getString(R.string.lianji_count, count));
            initAnimation(shuliang1);
            view1time = System.currentTimeMillis();
            showView1();
            mHandler.removeMessages(444);
            mHandler.sendEmptyMessageDelayed(444, 3000);

        } else if (info.getUserId().equals(tankuangView2.getTag())) {
            count++;
            ImageCache.getInstance(mContext).loadBitmapToView(headImage2, info.getUserLogo(), ViewUtil.getHeadImageSize_40(mContext));
            liwuIcon2.setImageResource(liwuId);
            dengjiText2.setText(info.getUserLevel());
            liwuNick2.setText(URLDecoder.decode(info.getNickName()));
            shuliang2.setText(getString(R.string.lianji_count, count));
            initAnimation(shuliang2);
            view2time = System.currentTimeMillis();
            showView2();
            mHandler.removeMessages(555);
            mHandler.sendEmptyMessageDelayed(555, 3000);
        } else {
            if (view1time > view2time) {
                count++;
                ImageCache.getInstance(mContext).loadBitmapToView(headImage2, info.getUserLogo(), ViewUtil.getHeadImageSize_40(mContext));
                dengjiText2.setText(info.getUserLevel());
                liwuIcon2.setImageResource(liwuId);
                liwuNick2.setText(URLDecoder.decode(info.getNickName()));
                shuliang2.setText(getString(R.string.lianji_count, count));
                initAnimation(shuliang2);
                tankuangView2.setTag(info.getUserId());
                view2time = System.currentTimeMillis();
                showView2();
                mHandler.removeMessages(555);
                mHandler.sendEmptyMessageDelayed(555, 3000);
            } else {
                count++;
                ImageCache.getInstance(mContext).loadBitmapToView(headImage1, info.getUserLogo(), ViewUtil.getHeadImageSize_40(mContext));
                dengjiText1.setText(info.getUserLevel());
                liwuIcon1.setImageResource(liwuId);
                liwuNick1.setText(URLDecoder.decode(info.getNickName()));
                shuliang1.setText(getString(R.string.lianji_count, count));
                initAnimation(shuliang1);
                tankuangView1.setTag(info.getUserId());
                view1time = System.currentTimeMillis();
                showView1();
                mHandler.removeMessages(444);
                mHandler.sendEmptyMessageDelayed(444, 3000);
            }
        }

        if (view1time > view2time) {
            liwuTanKuang.removeView(tankuangView1);
            liwuTanKuang.addView(tankuangView1);
        }

    }

    private GifView.OnStopListener stopListener = new GifView.OnStopListener() {
        @Override
        public void onStop() {
            hideDonghua();
        }
    };


    private void zuodonghua(EatShowUserInfo info, String giftId, int count) {
        tankuang(info, giftId, count);
        int gifUrl = 0;
        if (giftId.equals("0006")) {
            //礼盒
            gifUrl = R.raw.lihegif;

        } else if (giftId.equals("0007")) {
            //奖杯
            gifUrl = R.raw.jiangbei;
        } else if (giftId.equals("0014")) {
            //鲜花
            gifUrl = R.raw.xianhua;
        } else if (giftId.equals("0015")) {
            //笔记本
            gifUrl = R.raw.diannao;
        }

        if (gifUrl != 0) {
            if (liwuImageView.getVisibility() == View.VISIBLE) {
                return;
            }
            liwuImageView.setVisibility(View.VISIBLE);
            try {
                GifDrawable gifFromResource = new GifDrawable(getResources(), gifUrl);
                int frameint = gifFromResource.getDuration();
                liwuImageView.setImageDrawable(gifFromResource);
                mHandler.sendEmptyMessageDelayed(333, frameint);
            } catch (IOException e) {
                e.printStackTrace();
            }
//        if (gifUrl != 0) {
//            liwuImageView.setImageResource(-1);
//            if(liwuImageView.getVisibility()==View.VISIBLE){
//                return;
//            }
//            liwuImageView.setVisibility(View.VISIBLE);
//            liwuImageView.setMovieResource(gifUrl);
//            liwuImageView.setOnStopListener(stopListener);
           *//* Glide.with(RecorderActivity.this).load(gifUrl).asGif().diskCacheStrategy(DiskCacheStrategy.NONE).listener(new RequestListener<Integer, GifDrawable>() {
                @Override
                public boolean onException(Exception e, Integer integer, Target<GifDrawable> target, boolean b) {
                    return false;
                }

                @Override
                public boolean onResourceReady(GifDrawable gifDrawable, Integer integer, Target<GifDrawable> target, boolean b, boolean b1) {
                    int duration = 0;
                    try {
                        GifDrawable gif = gifDrawable;
                        GifDecoder decoder = gif.getDecoder();
                        for (int i = 0; i < gif.getFrameCount(); i++) {
                            duration += decoder.getDelay(i);
                            if (i == gif.getFrameCount() - 1) {
                                PalLog.e(TAG, "gif张数：" + i);
                            }
                        }
                        PalLog.e(TAG, "gif时长：" + duration);
                    } catch (Throwable e) {
                    }
                    mHandler.removeMessages(333);
                    mHandler.sendEmptyMessageDelayed(333, duration * 5);
                    return false;
                }
            }).into((Target) new GlideDrawableImageViewTarget(liwuImageView, 1));
            *//*
        }
    }

    @Override
    public void adapterLiwu(EatShowUserInfo info, TextView textView, String giftId, int count, boolean isZx) {
        if (!isZx) {
            zuodonghua(info, giftId, count);
        }
        String giftName = getGiftName(giftId);
        textView.setTextColor(getResources().getColor(R.color.orange_public));
        textView.setText("送了一个" + giftName);
    }

    @Override
    public void OnLiveStop() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (isFinishing()) {
                    return;
                }
                Dialog dialog = Utils.getOneButtonDialog(RecorderActivity.this,
                        getString(R.string.dialog_title_live_stop), false, false,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                setResult(RESULT_OK);
                                finish();
                            }
                        });
                dialog.show();
            }
        });
    }

    private String getGiftName(String giftId) {
        String giftName = null;
        if (giftId.equals("0001")) {
            giftName = "气球";
        } else if (giftId.equals("0002")) {
            giftName = "小蘑菇";
        } else if (giftId.equals("0003")) {
            giftName = "冰淇淋";
        } else if (giftId.equals("0004")) {
            giftName = "喜欢你";
        } else if (giftId.equals("0005")) {
            giftName = "手表";
        } else if (giftId.equals("0006")) {
            giftName = "礼盒";
        } else if (giftId.equals("0007")) {
            giftName = "奖杯";
        } else if (giftId.equals("0008")) {
            giftName = "鼓掌";
        } else if (giftId.equals("0009")) {
            giftName = "棒棒糖";
        } else if (giftId.equals("0010")) {
            giftName = "咖啡";
        } else if (giftId.equals("0011")) {
            giftName = "手绘画";
        } else if (giftId.equals("0012")) {
            giftName = "地球仪";
        } else if (giftId.equals("0013")) {
            giftName = "金牌教师";
        } else if (giftId.equals("0014")) {
            giftName = "鲜花";
        } else if (giftId.equals("0015")) {
            giftName = "笔记本";
        }
        return giftName;
    }
*/
}
